/**
 *  Copyright 2009-2010 Steven Ottenhoff (Dual-IT)
 * 
 *  This file is part of Clazzified.
 *
 *  Clazzified is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Clazzified is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Clazzified.  If not, see http://www.gnu.org/licenses/gpl.
 * 
 */
package nl.dualit.clazzified.store.clazz.db.dao;

import java.sql.ResultSet;
import java.util.Map;

import nl.dualit.clazzified.converter.clazz.ClazzConverterFactory;
import nl.dualit.clazzified.core.model.clazz.Clazz;
import nl.dualit.clazzified.store.clazz.ClazzFields;
import nl.dualit.clazzified.store.clazz.IClazzDao;
import nl.dualit.clazzified.store.db.AbstractDbHandler;

import org.apache.log4j.Logger;

public class ClazzDaoDb implements IClazzDao {
	
	Logger log = Logger.getLogger( ClazzDaoDb.class );
	private AbstractDbHandler handler;
	
	ClazzDaoDb( AbstractDbHandler handler ){
		
		this.handler = handler;
		
	}
	
	@Override
	public Map<ClazzFields,String> getClazzById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<ClazzFields, String> getClazzByName(String clazzName) {
		
		String sql = ClazzSql.selectClazz( ClazzFields.CLAZZ_NAME, clazzName );
		
		log.debug( "SQL: " + sql );
		
		ResultSet result = handler.selectStatement( sql );
		
		Map<ClazzFields,String> clazzData = ResultConverterSql.convertClazz( result );
		
		if( clazzData == null )
			throw new NullPointerException( "Null clazzData recieved from query" );
		
		return clazzData;
	}

	@Override
	public void deleteClazz( Long clazzId ) {
		
		if( clazzId == null )
			throw new NullPointerException( "Unable to remove clazz with null id" );
		
		String sql = ClazzSql.deleteClazz( ClazzFields.CLAZZ_ID, clazzId.toString() );
		
		log.debug( "SQL: " + sql );
		
		int result = handler.deleteStatement( sql );
		
		if( result == 0 )
			log.warn( "Clazz with id = " + clazzId + " cannot be removed" );
	}

	@Override
	public Long storeClazz( Map<ClazzFields,String> clazzMap ) {
		
		String sql =  ClazzSql.insertClazz( clazzMap );		
		
		log.debug( "SQL: " + sql );
		
		return handler.insertStatement( sql );
		
	}

	@Override
	public int updateClazz( Map<ClazzFields,String> clazzMap ) {
		
		String sql = ClazzSql.updateClazz( clazzMap );
		
		log.debug( "SQL:" + sql );
		
		return handler.updateStatement( sql );
		
	}
	

}
